package com.junko.home.resolver;

import com.alibaba.fastjson.JSONObject;
import com.junko.core.exception.BusinessException;
import com.junko.core.exception.LockedException;
import com.junko.core.exception.NoLoginException;
import com.junko.core.exception.NoPermissionException;
import com.junko.core.tool.ToolWeb;
import com.junko.model.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String actionKey = ToolWeb.getActionKey(request);
        String prefix;
        Map<String, Object> model = new HashMap<>();
        model.put("ex", ex);
        //不是逻辑错误、资源不存在异常、表单重复提交异常,就打印异常信息
        if (!(ex instanceof BusinessException)) {
            ex.printStackTrace();
        }
        //不是异步的，且不是异步文件上传、文件下载异常
        if (!ToolWeb.isAsync(request)) {
            if (ex instanceof LockedException){
                return new ModelAndView("/error/locked", model);
            }else if (ex instanceof NoLoginException){
                return new ModelAndView("/error/no_login", model);
            }else if (ex instanceof NoPermissionException){
                return new ModelAndView("/error/no_permission", model);
            }
            return new ModelAndView("/error/500", model);
        } else {
            //返回json
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            JsonResult jsonResult = JsonResult.fail(ex.getMessage());
            if (ex instanceof BusinessException) {
                jsonResult = JsonResult.fail(StringUtils.isEmpty(ex.getMessage())?"出错了":ex.getMessage());
            }
            PrintWriter writer=null;
            try {
                writer = response.getWriter();
                writer.write(JSONObject.toJSONString(jsonResult));
            } catch (IOException e) {
                logger.error("返回json异常:" + e.getMessage(), e);
            }finally {
                if(writer!=null){
                    writer.flush();
                    writer.close();
                }
            }
            return null;
        }
    }
}
